package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.LikesBehavior;
import com.heima.behavior.service.LikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikesBehaviorServiceImpl implements LikesBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.hotArticleScoreTopic}")
    private String hotArticleScoreTopic;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();//获取登陆的用户
        //判断参数
        if (dto == null ||user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建对象
        LikesBehavior likesBehavior = new LikesBehavior();
        likesBehavior.setArticleId(dto.getArticleId());//文章ID
        likesBehavior.setEquipmentId(dto.getEquipmentId());//设备ID
        likesBehavior.setUserId(user.getUserId());//用户ID
        likesBehavior.setCreatedTime(new Date());//创时间
        likesBehavior.setOperation(dto.getOperation());//操作类型:0 点赞 1 取消点赞
        if (dto.getOperation() == 0){
            mongoTemplate.save(likesBehavior);
        }else {
            //查询
            Query query = new Query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("userId").is(user.getUserId()));
            mongoTemplate.remove(query, LikesBehavior.class);
        }

        // 发送点赞消息到kafka
        UpdateArticleMessage updateArticleMessage = new UpdateArticleMessage();
        updateArticleMessage.setArticleId(dto.getArticleId());
        updateArticleMessage.setType(1);
        updateArticleMessage.setAdd(dto.getOperation() == 0 ? 1 : -1);

        String message = JSON.toJSONString(updateArticleMessage);
        kafkaTemplate.send(hotArticleScoreTopic, message);


        return ResponseResult.okResult();
    }



}
